package com.gopay.common.mq.producer;

import com.gopay.common.mq.configuration.MqConfig;
import com.gopay.common.mq.converter.JsonMsgConverter;
import com.gopay.common.mq.util.MqUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;

import javax.annotation.PostConstruct;
import javax.jms.Destination;
import java.io.Serializable;

/**
 * 生产者基类
 * @param <T>   消息类型
 */
public abstract class AbstractMsgProducer<T extends Serializable> {

    public Logger logger = LoggerFactory.getLogger(getClass());

    private JmsTemplate jmsTemplate;

    private Destination destination;

    @Autowired
    private MqConfig mqConfig;

    @PostConstruct
    public void postConstruct(){
        logger.info("Process postConstruct .");
    }


    public void sendMessage(T msg) {
        logger.info("Prepare send message to ActiveMq .");
        jmsTemplate.setMessageConverter(new JsonMsgConverter());

        beforeSendMsg(msg);

        logger.info("Do send Message !");
        try {
            jmsTemplate.convertAndSend(destination, msg);
        }catch (JmsException jmsEx){
            logger.error("Do send Message failed ! JmsException = {}", jmsEx);
            afterThrowing(jmsEx);
            throw new RuntimeException(jmsEx);
        }

        afterSendMsg(msg);
        logger.info("Send message success . ");
    }

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public Destination getDestination() {
        return destination;
    }

    protected void setDestination(Destination destination) {
        this.destination = MqUtils.appendSuffix(destination, mqConfig.SUFFIX);
    }

    protected void beforeSendMsg(T msg){
    }

    protected void afterSendMsg(T msg){
    }

    protected void afterThrowing(JmsException jmsEx){
    }

}
